package com.clas.liu.myapplication.view.activity.impl;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;

import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.info.Info;
import com.clas.liu.myapplication.model.entity.user.UserData;
import com.clas.liu.myapplication.presenter.impl.BasePresenter;
import com.clas.liu.myapplication.presenter.impl.EditPresenter;
import com.clas.liu.myapplication.view.activity.i.IEditActivity;
import com.clas.liu.myapplication.view.util.BitmapUtil;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * Created by liu on 2019/5/5.
 */

public class EditActivity extends BaseActivity<EditPresenter> implements IEditActivity, View.OnClickListener {

    private ImageView back;
    private ImageView submit;
    private ProgressBar loading;
    private EditText edit_text_tv;
    private ImageView add_pic_iv;
    private ImageView delete_pic_view;
    private EditText key_view;
    private TextView takePic;
    private TextView choosePic;
    private TextView cancel;

    private UserData userData;

    private boolean isEdit = false;
    private boolean hasPic = false;
    private String picUrl;
    private Uri tempUri;
    private Info info;
    private boolean picChanged = false;

    private Dialog choosePicDialog;

    String[] permissionPicture = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    int[] permissionRequest = {111, 222};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_layout);
        findView();
        init();
        setListener();
    }

    private void init() {
        info = (Info) getIntent().getSerializableExtra("info");
        userData = SaveUtil.<UserData>getFromLocal(getApplicationContext(), "user");
        if (userData == null || userData.getId() == 0) {
            showToast("当前登录异常，重新登录！", Toast.LENGTH_SHORT);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            this.finish();
        }
        initDialog();
        if (info != null)
            initInfo(info);
    }

    private void initDialog() {
        choosePicDialog = new Dialog(this, R.style.DialogTheme);
        choosePicDialog.setContentView(View.inflate(this, R.layout.dialog_pic_layout, null));
        Window window = choosePicDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.add_dialog_style);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        takePic = choosePicDialog.findViewById(R.id.tv_take_photo);
        choosePic = choosePicDialog.findViewById(R.id.tv_take_pic);
        cancel = choosePicDialog.findViewById(R.id.tv_cancel);
    }

    private void initInfo(Info info) {
        isEdit = true;
        edit_text_tv.setText(info.getText());
        if (info.getPic() != null && !info.getPic().equals("") && !info.getPic().equals("null")) {
            Picasso.with(this).load(info.getPic()).placeholder(R.mipmap.loading).into(add_pic_iv);
            hasPic = true;
            delete_pic_view.setVisibility(View.VISIBLE);
            picUrl = info.getPic();
        }
        if (info.getKey_word() != null && !info.getKey_word().equals("")) {
            key_view.setText(info.getKey_word());
        }

    }

    public void deletePic() {
        Picasso.with(this).load(R.mipmap.add_pic).into(add_pic_iv);
        delete_pic_view.setVisibility(View.GONE);
        picUrl = "";
        hasPic = false;
        if (info==null || info.getPic()==null || info.getPic().equals("") || info.getPic().equals("null"))
            picChanged = false;
    }

    private void setListener() {
        back.setOnClickListener(this);
        submit.setOnClickListener(this);
        add_pic_iv.setOnClickListener(this);
        delete_pic_view.setOnClickListener(this);
        takePic.setOnClickListener(this);
        choosePic.setOnClickListener(this);
        cancel.setOnClickListener(this);

    }

    private void findView() {
        back = findViewById(R.id.edit_back_bt);
        submit = findViewById(R.id.edit_submit);
        loading = findViewById(R.id.edit_submit_pb);
        edit_text_tv = findViewById(R.id.edit_text_tv);
        add_pic_iv = findViewById(R.id.edit_pic);
        delete_pic_view = findViewById(R.id.edit_delete_pic);
        key_view = findViewById(R.id.edit_key_tv);
    }

    @Override
    public void failBecauseNetReturn(int code) {
        hideLoadingView();
        showToast(code + "发布失败！！", Toast.LENGTH_SHORT);
    }

    @Override
    public void addReturn() {
        hideLoadingView();
        showToast("发布成功！",Toast.LENGTH_SHORT);
        this.finish();
    }

    @Override
    public void editReturn() {
        hideLoadingView();
        showToast("修改成功！",Toast.LENGTH_SHORT);
        setResult(200);
        this.finish();
    }

    @Override
    protected EditPresenter getPresenter() {
        return new EditPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_back_bt:
                this.finish();
                break;
            case R.id.edit_submit:
                showLoadingView();
                startPost();
                break;
            case R.id.edit_pic:
                CheckPic();
                break;
            case R.id.edit_delete_pic:
                deletePic();
                break;
            case R.id.tv_cancel:
                choosePicDialog.dismiss();
                break;
            case R.id.tv_take_photo:
                //拍照
                checkPermission(1);
                choosePicDialog.dismiss();
                break;
            case R.id.tv_take_pic:
                //从相册获取
                checkPermission(0);
                choosePicDialog.dismiss();
                break;
        }
    }

    public void showLoadingView() {
        loading.setVisibility(View.VISIBLE);
        submit.setVisibility(View.GONE);
    }

    public void hideLoadingView() {
        loading.setVisibility(View.GONE);
        submit.setVisibility(View.VISIBLE);
    }

    /**
     * 检查权限
     *
     * @param type 类型
     */
    private void checkPermission(int type) {
        String[] permission = {permissionPicture[type]};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int cp2 = ContextCompat.checkSelfPermission(this, permissionPicture[type]);
            if (cp2 != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, permission, permissionRequest[type]);
            } else {
                switch (type) {
                    case 0:
                        getPhoto();
                        break;
                    case 1:
                        takePhoto();
                        break;
                }
            }
        } else {
            switch (type) {
                case 0:
                    getPhoto();
                    break;
                case 1:
                    takePhoto();
                    break;
            }
        }
    }

    /**
     * 打开相机
     */
    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        tempUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(intent, permissionRequest[1]);
        file.deleteOnExit();
    }

    /**
     * 从本地图片库选择图片
     */
    private void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, permissionRequest[0]);

    }

    private void CheckPic() {
        if (hasPic)
            showPicBig();
        else {
            if (choosePicDialog != null)
                choosePicDialog.show();
        }
    }

    public void showPicBig() {
        Intent intent;
        if (picUrl != null && !"".equals(picUrl)) {
            if (picChanged) {
                intent = new Intent(this, ImageViewActivity.class);
                intent.putExtra("url", tempUri.toString());
                startActivity(intent);
            }else {
                intent = new Intent(this, ImageViewActivity.class);
                intent.putExtra("url", picUrl);
                startActivity(intent);
            }
        }
    }

    private void startPost() {
        if (info == null)
            info = new Info();
        if(TextUtils.isEmpty(edit_text_tv.getText().toString())) {
            showToast("亲，还是要说点话！",Toast.LENGTH_SHORT);
            hideLoadingView();
            return;
        }
        if (userData.getBanded() == 1) {
            showToast("当前账户已被举报，管理员审核通过并禁言！",Toast.LENGTH_SHORT);
            return;
        }
        info.setText(edit_text_tv.getText().toString());
        info.setKey_word(key_view.getText().toString());
        if (hasPic) {
            if (picChanged) {
                picUrl = BitmapUtil.imageToBase64(this,picUrl);
                info.setPic(picUrl);
            }
        }else {
            info.setPic("");
        }
        info.setRelease_time(String.valueOf(System.currentTimeMillis()));
        if (info.getId() == 0) {
            info.setCategory(getIntent().getIntExtra("category", 4));
            info.setUser_id(userData.getId());
        }
        if (info.getName() == null)
            info.setName("");
        if (info.getSex() == null)
            info.setSex("");
        if (info.getHead() == null)
            info.setHead("");
        if (isEdit)
            mPresenter.editInfo(info);
        else mPresenter.addInfo(info);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == permissionRequest[0]) {
                takePhoto();
            } else {
                getPhoto();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = null;
        if (requestCode == permissionRequest[0]) {
            if (data == null)
                return;
            tempUri = data.getData();
        } else {
            if (requestCode == permissionRequest[1])
                if (resultCode == 0)
                    tempUri = null;
        }
        if (tempUri != null) {
            picUrl = tempUri.toString();
            //                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), tempUri);
            bitmap = BitmapUtil.getBitmapFromUri(this,tempUri);
            if (bitmap != null) {
                add_pic_iv.setImageBitmap(bitmap);
                delete_pic_view.setVisibility(View.VISIBLE);
                picUrl = BitmapUtil.saveImageToGallery(this, bitmap);
                hasPic = true;
                picChanged = true;
            } else {
                Toast.makeText(this, "获取图片失败！", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
